<template>
  <div
    class="vi-iframe-drag"
    ref="viIframeContainer"
    @dragenter="dragEnterCanvas"
  >
    <div class="vi-iframe-drag-container">
      <vi-draggable :options="options">
        <slot></slot>
      </vi-draggable>
      <!--:data-id="index"-->
      <div ref="viIframeMedium"><div/></div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import ViDraggable from './ViDraggable.vue'
import Sortable from '@/components/Draggable/Sortable'

// 激活iframe画布拖拽响应
let dragEl
let isPrepareDraggable = false
let parentPrepare = false
const viIframeMedium = ref()

/**
 * 拖拽进入画布时，进行代理唤醒
 */
function dragEnterCanvas () {
  if (!parentPrepare || isPrepareDraggable) {
    return
  }
  isPrepareDraggable = true
  prepareDraggable()
}
/**
 * 激活画布拖拽
 */
function prepareDraggable () {
  const downEvt = new PointerEvent('pointerdown', {
    bubbles: true,
    cancelable: true,
    width: 100,
    height: 100,
    isPrimary: true
  })
  dragEl.dispatchEvent(downEvt)
  const startEvt = new DragEvent('dragstart', { bubbles: true })
  dragEl.dispatchEvent(startEvt)
}
/**
 * 结束拖拽
 */
function endDraggable () {
  if (!isPrepareDraggable) {
    return
  }
  dragEl.dispatchEvent(new DragEvent('dragend'))
  isPrepareDraggable = false
  parentPrepare = false
}
/**
 * 接收父组件消息
 */
function onParentMsg () {
  window.onmessage = (e) => {
    switch (e.data.type) {
    case 'dragStart':
      parentPrepare = true
      break
    case 'unChoose':
    case 'onDrop':
      endDraggable()
      break
    case 'onDragleave': {
      const downEvt = new DragEvent('dragenter', {})
      viIframeMedium.value.dispatchEvent(downEvt)
      break
    }
    }
  }
}
// 拖拽对象注册
let sortable
const options = {
  group: {
    name: 'canvas',
    pull: 'clone',
    put: false
  }
}
onMounted(() => {
  onParentMsg()
  dragEl = viIframeMedium.value.firstElementChild
  sortable = new Sortable(viIframeMedium.value, options)
})
// 拖拽对象声明
</script>

<style scoped lang="less">
.vi-iframe-drag {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  background-color: rgb(237,239,243);
  &-container {
    width: 100%;
    height: 100%;
    padding: 20px;
    background-color: white;
    box-shadow: 0 1px 4px 0 rgba(31,50,88, 0.13);
  }
}
</style>
